package yxy.game.pm2.module.shop;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.itemshop;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;

import java.util.ArrayList;
import java.util.Map;

/** 商店 道具商店 */
public class ItemShopModule extends ShopModule {

	// static===========================================================================

	public static String key(String playerCode) {
		return String.format(key(), playerCode, "ITEM");
	}

	public static ItemShopModule get(String playerCode) {
		try {
			ItemShopModule module = getv(key(playerCode));
			if (module == null) {
				module = MySQLCacheDAO.getV(key(playerCode), ItemShopModule.class);
				if(module != null){module.set();}//把数据同步到redis
			}

			String md5 = DataCenter.getMD5(itemshop.class);
			if (module == null) {
				module = create(playerCode, md5);
			} else {
				module.checkMD5(md5);
			}
			return module;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static ItemShopModule create(String playerCode, String md5) {
		ItemShopModule module = new ItemShopModule();
		module.setPlayerCode(playerCode);
		module.setDataMD5(md5);
		module.shuffleGoods();
		module.set();
		return module;
	}

	// extends===========================================================================

	@Override
	protected void shuffleGoods() {
		Map<String, itemshop> datas = DataCenter.getAllData(itemshop.class);
		DateTime now = DateTime.now();
		ArrayList<Goods> goodslist = new ArrayList<>();
		for (itemshop data : datas.values()) {
			Goods goods = new Goods();
			goods.setId(data.getId());
			goods.setDataId(data.getId());
			goods.setSell(0);
			goods.setUpdateTime(now);
			goodslist.add(goods);
		}
		setGoods(goodslist);
	}

	//存储到数据库的方法
	public static void saveToDB(String playerCode) {
		try {
			String key = key(playerCode);
			if (touch(key).isExists()) {
				ItemShopModule itemShopModule = getv(key(playerCode));
				if(itemShopModule != null)MySQLCacheDAO.setV(key, itemShopModule);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//从redis移走数据的操作
	public static void removeAllFromRedis(String playerCode) {
		try {
			touch(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void set() {
		try {
			setv(key(getPlayerCode()), this);
		} catch (RedisException e) {
		}
	}

}